package com.hskn.hss.module.alarmperson.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.page.TableDataInfo;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.alarmHandleLog.domain.AlarmHandleLog;
import com.hskn.hss.module.alarmHandleLog.service.IAlarmHandleLogService;
import com.hskn.hss.module.alarmcar.entity.AlarmCar;
import com.hskn.hss.module.alarmperson.entity.AlarmPerson;
import com.hskn.hss.module.alarmperson.entity.AlarmPersonCharts;
import com.hskn.hss.module.alarmperson.mapper.AlarmPersonMapper;
import com.hskn.hss.module.alarmperson.service.IAlarmPersonService;
import com.hskn.hss.module.alarmperson.vo.AlarmPersonTableDetailVO;
import com.hskn.hss.module.carviolation.entity.CarViolation;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.dlbjviolation.entity.DlbjViolation;
import com.hskn.hss.module.dlbjviolation.mapper.DlbjViolationMapper;
import com.hskn.hss.module.messageFlowRecords.domain.MessageFlowRecords;
import com.hskn.hss.module.messageFlowRecords.service.IMessageFlowRecordsService;
import com.hskn.hss.module.tlemployee.entity.TlEmployee;
import com.hskn.hss.module.tlemployee.service.ITlEmployeeService;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.utils.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-21
 */
@Service
public class AlarmPersonServiceImpl extends ServiceImpl<AlarmPersonMapper, AlarmPerson> implements IAlarmPersonService {

    @Resource
    private AlarmPersonMapper alarmPersonMapper;
    @Resource
    private DlbjViolationMapper dlbjViolationMapper;
    @Autowired
    private IAlarmHandleLogService alarmHandleLogService;
    @Resource
    private UserMapper userMapper;
    @Autowired
    private ITlEmployeeService employeeService;
    @Autowired
    private IMessageFlowRecordsService messageFlowRecordsService;
    @Autowired
    LocationUtils locationUtil;
    @Autowired
    ISysDepartService departService;


    @Override
    @DataScope(deptAlias = "dep_id", userAlias = "deal_uid")
    public JSONObject mList(BaseEntity entity, JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        JSONObject json = new JSONObject();
        QueryWrapper<AlarmPerson> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(AlarmPerson::getCreateTime);
        if (entity.getParams().containsKey("dataScope")&&StringUtils.isNotEmpty(entity.getParams().get("dataScope"))) {
            queryWrapper.lambda().apply(entity.getParams().get("dataScope").toString());
        }
        String alarmPersonId = params.getString("alarmPersonId");
        if (StringUtils.isNotEmpty(alarmPersonId)) {
            queryWrapper.lambda().eq(AlarmPerson::getAlarmPersonId, alarmPersonId);
        }
        String type = params.getString("type");
        if (StringUtils.isNotEmpty(type)) {
            queryWrapper.lambda().eq(AlarmPerson::getPersonTypeName, type);
        }
        String personId = params.getString("personId");
        if (StringUtils.isNotEmpty(personId)) {
            queryWrapper.lambda().eq(AlarmPerson::getPersonId, personId);
        }
        String alarmTypeId = params.getString("alarmTypeId");
        if (StringUtils.isNotEmpty(alarmTypeId)) {
            queryWrapper.lambda().eq(AlarmPerson::getAlarmTypeId, alarmTypeId);
        }
        String alarmTypeName = params.getString("alarmTypeName");
        if (StringUtils.isNotEmpty(alarmTypeName)) {
            queryWrapper.lambda().like(AlarmPerson::getAlarmTypeName, alarmTypeName);
        }
        String startDate = params.getString("startDate");
        String endDate = params.getString("endDate");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            queryWrapper.lambda().between(AlarmPerson::getAlarmTime, startDate + " 00:00:00", endDate + " 23:59:59");
        }
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        Page<AlarmPerson> alarmPersonPage = new Page<>(page, size, true);
        IPage<AlarmPerson> iPage = alarmPersonMapper.selectPage(alarmPersonPage, queryWrapper);
        Map<String, TlEmployee> employeeMap=employeeService.getEmpMap(new QueryWrapper<>());
        List<AlarmPerson> list=iPage.getRecords();
        for(AlarmPerson alarmPerson:list){
            if (employeeMap.containsKey(alarmPerson.getPersonId())){
                alarmPerson.setEmpHeadPortraitAlarm(employeeMap.get(alarmPerson.getPersonId()).getPersonphoto());
            }
            MessageFlowRecords messageFlowRecords = new MessageFlowRecords();
            messageFlowRecords.setMessageId(alarmPerson.getAlarmPersonId());
            messageFlowRecords.setKind(1);
            messageFlowRecords.setSubjectType(1);
            messageFlowRecords.setUserId(uid);
            List<MessageFlowRecords> messageFlowRecords1 = messageFlowRecordsService.selectMessageFlowRecordsList(messageFlowRecords);
            if ((Objects.nonNull(messageFlowRecords1) && messageFlowRecords1.size() > 0) || alarmPerson.getAlarmTime().compareTo(DateUtil.parseDateTime(AttributeUtils.timeCompletion(DateUtil.formatDate(new Date()), 's'))) < 0){
                alarmPerson.setIsRead(1);
            } else {
                alarmPerson.setIsRead(0);
            }
        }
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("list", iPage.getRecords());
        return json;
    }

    @Override
    public JSONObject getAbnormal() {

        JSONObject result = new JSONObject();

        String day = DateUtil.formatDate(new Date());
        String startTime = AttributeUtils.timeCompletion(day, 's');
        String endTime = AttributeUtils.timeCompletion(day, 'e');

        QueryWrapper<AlarmPerson> alarmPersonQueryWrapper = new QueryWrapper<>();
        alarmPersonQueryWrapper.lambda().ge(AlarmPerson::getAlarmTime,startTime);
        alarmPersonQueryWrapper.lambda().le(AlarmPerson::getAlarmTime,endTime);
        List<AlarmPerson> alarmPersons = alarmPersonMapper.selectList(alarmPersonQueryWrapper);

        //人报警
        Map<String, Long> alarmPersonMap = alarmPersons.stream().collect(Collectors.groupingBy(AlarmPerson::getAlarmTypeName, Collectors.counting()));

        Map<String,Long> personAlarmMap = new HashMap();
        personAlarmMap.put("离线",0L);
        alarmPersonMap.keySet().forEach(t->{
            if ("离线".equals(t)){
                personAlarmMap.put("离线",Long.parseLong(String.valueOf(alarmPersonMap.get(t))));
            }
        });

        // 转list
        List<Map.Entry<String,Long>> personAlarmList = new ArrayList<>(personAlarmMap.entrySet());
        personAlarmList.sort(Comparator.comparing(Map.Entry::getValue));
        //排序
        Collections.sort(personAlarmList, (o1, o2) -> {
            Long d1 = o1.getValue();
            Long d2 = o2.getValue();
            return d2.compareTo(d1);
        });

        //格式化list
        List<String> alarmPersonList = new ArrayList<>();
        personAlarmList.forEach(t->{
            alarmPersonList.add(t.getKey() + ":" + t.getValue());
        });

        result.put("personAlarmNum", alarmPersons.size());
        result.put("personAlarmList", alarmPersonList);

        QueryWrapper<DlbjViolation> dlbjViolationQueryWrapper = new QueryWrapper<>();
        dlbjViolationQueryWrapper.lambda().ge(DlbjViolation::getDate,startTime);
        dlbjViolationQueryWrapper.lambda().le(DlbjViolation::getDate,endTime);
        List<DlbjViolation> dlbjViolations = dlbjViolationMapper.selectList(dlbjViolationQueryWrapper);

        //人的违规
        Map<String, Long> violationCarMap = dlbjViolations.stream().collect(Collectors.groupingBy(DlbjViolation::getViolationTypeName, Collectors.counting()));
        Map<String, Long> dlbjViolationMap = new HashMap();
        dlbjViolationMap.put("停留",0L);
        dlbjViolationMap.put("离岗",0L);
        dlbjViolationMap.put("聚众",0L);
        violationCarMap.keySet().forEach(t->{
            if ("停留".equals(t)){
                dlbjViolationMap.put("停留",dlbjViolationMap.get(t));
            } else if ("离岗".equals(t)){
                dlbjViolationMap.put("离岗",dlbjViolationMap.get(t));
            } else if ("聚众".equals(t)){
                dlbjViolationMap.put("聚众",dlbjViolationMap.get(t));
            }
        });

        // 转list
        List<Map.Entry<String,Long>> dlbjViolationList = new ArrayList<>(dlbjViolationMap.entrySet());
        dlbjViolationList.sort(Comparator.comparing(Map.Entry::getValue));
        //排序
        Collections.sort(dlbjViolationList, (o1, o2) -> {
            Long d1 = o1.getValue();
            Long d2 = o2.getValue();
            return d2.compareTo(d1);
        });

        //格式化list
        List<String> violationCarList = new ArrayList<>();
        dlbjViolationList.forEach(t->{
            violationCarList.add(t.getKey() + ":" + t.getValue());
        });

        result.put("personViolationNum", dlbjViolations.size());
        result.put("personViolationList", violationCarList);

        return result;
    }

    @Override
    public void deal(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("alarmPersonIds"))) {
            throw new HssException("参数错误");
        }
        String alarmPersonIdStr = params.getString("alarmPersonIds");
        String[] alarmPersonIds = alarmPersonIdStr.split(",");
        QueryWrapper<AlarmPerson> alarmPersonQueryWrapper=new QueryWrapper<>();
        alarmPersonQueryWrapper.lambda().in(AlarmPerson::getAlarmPersonId,alarmPersonIds);
        List<AlarmPerson> alarmPersonList=alarmPersonMapper.selectList(alarmPersonQueryWrapper);
        User user=userMapper.selectById(uid);
        Map<String,AlarmPerson> alarmPersonMap=null;
        if(!alarmPersonList.isEmpty()){
            alarmPersonMap= GroupingByUtils.getGroupingForMapEntity(alarmPersonList,AlarmPerson::getAlarmPersonId
                    , Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }else {
            alarmPersonMap=new HashMap<>();
        }
        List<AlarmPerson> alarmPersons = new ArrayList<>();
        AlarmHandleLog alarmHandleLog=null;
        List<AlarmHandleLog> alarmHandleLogList=new LinkedList<>();
        for (String alarmPersonId : alarmPersonIds) {
            AlarmPerson alarmPerson = new AlarmPerson(alarmPersonId, params.getString("dealType"), params.getString("dealRemark"), uid);
            alarmPersons.add(alarmPerson);
            if(alarmPersonMap.containsKey(alarmPersonId)){
                alarmPerson=alarmPersonMap.get(alarmPersonId);
                alarmHandleLog =getAlarmHandleLog(alarmPerson,params,uid,user);
                alarmHandleLogList.add(alarmHandleLog);
            }
        }
        alarmHandleLogService.saveBatch(alarmHandleLogList);
        updateBatchById(alarmPersons);
    }


    private AlarmHandleLog getAlarmHandleLog(AlarmPerson alarmCar , JSONObject params, String uid , User user){
        AlarmHandleLog alarmHandleLog=new AlarmHandleLog(StringUtils.uuid(),alarmCar.getAlarmPersonId(),alarmCar.getPersonId(),alarmCar.getPersonName(),alarmCar.getPersonTypeId(),alarmCar.getPersonTypeName(),
                new Date(),alarmCar.getDepId(),alarmCar.getDepName(),alarmCar.getAlarmTypeId(),alarmCar.getAlarmTypeName(), params.getString("dealType"),uid,user!=null?user.getName():"",
                params.getString("dealRemark"),alarmCar.getContent(),alarmCar.getAlarmStartTime(),alarmCar.getAlarmEndTime(),alarmCar.getIsKeep(),alarmCar.getLng(),alarmCar.getLat(),
                alarmCar.getAlarmTime(),alarmCar.getAddress(),"0","emp"

        );
        return alarmHandleLog;
    }

    @Override
    public JSONObject getPersonnelPolice(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        QueryWrapper<AlarmPerson> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("alarm_type_name");
        queryWrapper.select("alarm_type_name");
        if (params != null) {
            if (StringUtils.isNotEmpty(params.getString("type")) && params.getString("type") != null) {
                queryWrapper.lambda().eq(AlarmPerson::getAlarmTypeId, params.getString("type"));
            }
            if (StringUtils.isNotEmpty(params.getString("beginTime")) && params.getString("beginTime") != null && StringUtils.isNotEmpty(params.getString("endTime")) && params.getString("endTime") != null) {
                queryWrapper.lambda().between(AlarmPerson::getCreateTime, params.getString("beginTime"), params.getString("endTime"));
            }
        }
        queryWrapper.lambda().groupBy(AlarmPerson::getAlarmTypeName);
        List<Object> legendData = this.listObjs(queryWrapper);
        json.put("legendData", legendData);

        QueryWrapper<AlarmPerson> queryWrapperx = new QueryWrapper<>();
        queryWrapperx.isNotNull("person_name");
        queryWrapperx.select("person_name");
        if (params != null) {
            if (StringUtils.isNotEmpty(params.getString("persionId")) && params.getString("persionId") != null) {
                queryWrapperx.lambda().eq(AlarmPerson::getPersonId, params.getString("persionId"));
            }
            if (StringUtils.isNotEmpty(params.getString("beginTime")) && params.getString("beginTime") != null && StringUtils.isNotEmpty(params.getString("endTime")) && params.getString("endTime") != null) {
                queryWrapperx.lambda().between(AlarmPerson::getCreateTime, params.getString("beginTime"), params.getString("endTime"));
            }
        }
        queryWrapperx.lambda().groupBy(AlarmPerson::getPersonName);
        List<Object> xAxisData = this.listObjs(queryWrapperx);
        json.put("xAxisData", xAxisData);

        QueryWrapper<AlarmPerson> queryWrappers = new QueryWrapper<>();
        queryWrappers.select("person_name as xAxisData,alarm_type_name as legendData,count(1) as data");
        if (params != null) {
            if (StringUtils.isNotEmpty(params.getString("type")) && params.getString("type") != null) {
                queryWrappers.lambda().eq(AlarmPerson::getAlarmTypeId, params.getString("type"));
            }
            if (StringUtils.isNotEmpty(params.getString("persionId")) && params.getString("persionId") != null) {
                queryWrappers.lambda().eq(AlarmPerson::getPersonId, params.getString("persionId"));
            }
            if (StringUtils.isNotEmpty(params.getString("beginTime")) && params.getString("beginTime") != null && StringUtils.isNotEmpty(params.getString("endTime")) && params.getString("endTime") != null) {
                queryWrappers.lambda().between(AlarmPerson::getCreateTime, params.getString("beginTime"), params.getString("endTime"));
            }
        }
        queryWrappers.lambda().groupBy(AlarmPerson::getPersonName, AlarmPerson::getAlarmTypeName);
        List<Map<String, Object>> alarms = this.listMaps(queryWrappers);
        List<Map<String, List>> seriesData = new ArrayList<Map<String, List>>();
        if (!legendData.isEmpty() && legendData != null) {
            for (Object legendDatas : legendData) {
                List list = new ArrayList();
                for (Map<String, Object> alarm : alarms) {
                    if (alarm.get("legendData") != null) {
                        if (alarm.get("legendData").equals(legendDatas)) {
                            list.add(alarm.get("data"));
                        } else {
                            if (!this.iset(alarms, legendDatas, alarm.get("xAxisData"))) {
                                list.add(0);
                            }
                        }
                    }
                }
                Map<String, List> map = new HashMap<String, List>();
                map.put(legendDatas.toString(), list);
                seriesData.add(map);
            }
        }
        json.put("seriesData", seriesData);
        return json;
    }

    private boolean iset(List<Map<String, Object>> alarms, Object legendData, Object xAxisData) {
        for (Map<String, Object> alarm : alarms) {
            if (alarm.get("legendData") != null && alarm.get("xAxisData") != null) {
                if (alarm.get("legendData").equals(legendData) && alarm.get("xAxisData").equals(xAxisData)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public JSONObject collectList(JSONObject params) throws HssException {

        JSONObject res = new JSONObject();
        Long page = (StringUtils.isEmpty(params.getLong("page")) || params.getLong("page") == 0) ? 1 : params.getLong("page");
        Long size = (StringUtils.isEmpty(params.getLong("size")) || params.getLong("size") == 0) ? 10 : params.getLong("size");
        params.put("offset", (page - 1) * size);
        params.put("limit", size);
        List<Map<String, Object>> list = alarmPersonMapper.collectList(params);
        long count = alarmPersonMapper.collectListCount(params);
        res.put("list", list);
        res.put("total", count);
        res.put("current", page);
        res.put("pages", (int) Math.ceil(count / size));
        res.put("size", list.size());
        return res;
    }


    @Override
    public List<AlarmPersonCharts> selectAlarmPersonForChartsTable(AlarmPerson alarmPerson) {
        if (Objects.isNull(alarmPerson.getAlarmStartTime())){
            alarmPerson.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            alarmPerson.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmPerson.getAlarmStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(alarmPerson.getAlarmEndTime())){
            alarmPerson.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            alarmPerson.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmPerson.getAlarmEndTime())+" 23:59:59"));
        }
        List<AlarmPersonCharts> bTableList = alarmPersonMapper.selectAlarmPersonForChartsTable(alarmPerson);

        if (Objects.nonNull(bTableList) && bTableList.size()>0){
            QueryWrapper<AlarmPerson> alarmPersonQueryWrapper=new QueryWrapper<>();
            if (StringUtils.isNotEmpty(alarmPerson.getPersonName())){
                alarmPersonQueryWrapper.lambda().eq(AlarmPerson::getPersonName,alarmPerson.getPersonName());
            }
            if (StringUtils.isNotEmpty(alarmPerson.getAlarmTypeName())){
                alarmPersonQueryWrapper.lambda().eq(AlarmPerson::getAlarmTypeName,alarmPerson.getAlarmTypeName());
            }
            if (StringUtils.isNotEmpty(alarmPerson.getDepId())) {
                alarmPersonQueryWrapper.lambda().in(AlarmPerson::getDepId, alarmPerson.getDepIds());
            }

            alarmPersonQueryWrapper.lambda().ge(AlarmPerson::getAlarmTime,alarmPerson.getAlarmStartTime());
            alarmPersonQueryWrapper.lambda().le(AlarmPerson::getAlarmTime,alarmPerson.getAlarmEndTime());

            List<AlarmPerson> alarmPersonList = alarmPersonMapper.selectList(alarmPersonQueryWrapper);

            alarmPersonList.forEach(t->{
                t.setAlarmDate(DateUtil.formatDate(t.getAlarmTime()));
            });
            Map<String, List<AlarmPerson>> alarmPersonMap = alarmPersonList.stream().collect(Collectors.groupingBy(AlarmPerson::getPersonName));

            Map<String, Map<String, List<AlarmPerson>>> map2 = new HashMap<>();
            alarmPersonMap.keySet().forEach(t->{
                List<AlarmPerson> alarmPersons = alarmPersonMap.get(t);
                Map<String, List<AlarmPerson>> alarmTypePersonMap = alarmPersons.stream().collect(Collectors.groupingBy(AlarmPerson::getAlarmTypeName));
                map2.put(alarmPersons.get(0).getPersonName(),alarmTypePersonMap);
            });

            for (AlarmPersonCharts alarmPersonCharts:bTableList
            ) {
                if (Objects.nonNull(map2.get(alarmPersonCharts.getPersonName()).get("离线"))){
                    alarmPersonCharts.setLxCount(map2.get(alarmPersonCharts.getPersonName()).get("离线").size());
                }
                if (Objects.nonNull(map2.get(alarmPersonCharts.getPersonName()).get("SOS求救"))){
                    alarmPersonCharts.setSOSCount(map2.get(alarmPersonCharts.getPersonName()).get("SOS求救").size());
                }
            }
        }
        return bTableList;
    }

    @Override
    public List<List<Object>> selectAlarmPersonForCharts(AlarmPerson alarmPerson) throws ParseException {
        if (Objects.isNull(alarmPerson.getAlarmStartTime())){
            alarmPerson.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            alarmPerson.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmPerson.getAlarmStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(alarmPerson.getAlarmEndTime())){
            alarmPerson.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            alarmPerson.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmPerson.getAlarmEndTime())+" 23:59:59"));
        }
        Date startDate = alarmPerson.getAlarmStartTime();
        Date endDate = alarmPerson.getAlarmEndTime();
        List<AlarmPersonCharts> bTableList = alarmPersonMapper.selectAlarmPersonForCharts(alarmPerson);
        if (Objects.nonNull(bTableList) && bTableList.size()>0){
            QueryWrapper<AlarmPerson> alarmPersonQueryWrapper=new QueryWrapper<>();
            if (StringUtils.isNotEmpty(alarmPerson.getPersonName())){
                alarmPersonQueryWrapper.lambda().eq(AlarmPerson::getPersonName,alarmPerson.getPersonName());
            }
            if (StringUtils.isNotEmpty(alarmPerson.getAlarmTypeName())){
                alarmPersonQueryWrapper.lambda().eq(AlarmPerson::getAlarmTypeName,alarmPerson.getAlarmTypeName());
            }
            if (StringUtils.isNotEmpty(alarmPerson.getDepId())) {
                alarmPersonQueryWrapper.lambda().in(AlarmPerson::getDepId, alarmPerson.getDepIds());
            }
            if ("2".equals(alarmPerson.getDateType())){
                alarmPersonQueryWrapper.lambda().ge(AlarmPerson::getAlarmTime,bTableList.get(0).getAlarmTime() + "-01 00:00:00");
                alarmPersonQueryWrapper.lambda().le(AlarmPerson::getAlarmTime,bTableList.get(bTableList.size()-1).getAlarmTime() + "-31 23:59:59");
            } else {
                alarmPersonQueryWrapper.lambda().ge(AlarmPerson::getAlarmTime,bTableList.get(0).getAlarmTime() + " 00:00:00");
                alarmPersonQueryWrapper.lambda().le(AlarmPerson::getAlarmTime,bTableList.get(bTableList.size()-1).getAlarmTime() + " 23:59:59");
            }

            List<AlarmPerson> alarmPersonList = alarmPersonMapper.selectList(alarmPersonQueryWrapper);

            if ("2".equals(alarmPerson.getDateType())){
                alarmPersonList.forEach(t->{
                    t.setAlarmDate(DateUtil.format(t.getAlarmTime(),DatePattern.NORM_MONTH_PATTERN));
                });
            } else {
                alarmPersonList.forEach(t->{
                    t.setAlarmDate(DateUtil.formatDate(t.getAlarmTime()));
                });
            }

            Map<String, List<AlarmPerson>> alarmPersonMap = alarmPersonList.stream().collect(Collectors.groupingBy(AlarmPerson::getAlarmDate));

            Map<String, Map<String, List<AlarmPerson>>> map2 = new HashMap<>();
            alarmPersonMap.keySet().forEach(t->{
                List<AlarmPerson> alarmPersons = alarmPersonMap.get(t);
                Map<String, List<AlarmPerson>> alarmTypePersonMap = alarmPersons.stream().collect(Collectors.groupingBy(AlarmPerson::getAlarmTypeName));
                map2.put(alarmPersons.get(0).getAlarmDate(),alarmTypePersonMap);
            });

            for (AlarmPersonCharts alarmPersonCharts:bTableList
            ) {
                if (Objects.nonNull(map2.get(alarmPersonCharts.getAlarmTime()).get("离线"))){
                    alarmPersonCharts.setLxCount(map2.get(alarmPersonCharts.getAlarmTime()).get("离线").size());
                }
                if (Objects.nonNull(map2.get(alarmPersonCharts.getAlarmTime()).get("SOS求救"))){
                    alarmPersonCharts.setSOSCount(map2.get(alarmPersonCharts.getAlarmTime()).get("SOS求救").size());
                }
            }
        }
        if ("2".equals(alarmPerson.getDateType())){
            return getSelectAlarmForChartsByMonth(startDate, endDate, bTableList);
        } else {
            return getSelectAlarmForCharts(startDate, endDate, bTableList);
        }
    }

    private  List<List<Object>> getSelectAlarmForCharts(Date startDate,Date endDate,List<AlarmPersonCharts> bTableList) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<Object> resList = new ArrayList<>();
        List<List<Object>> resList2 = new ArrayList<>();
        List<String> dateStringList = new ArrayList<>();
        dateStringList = Tools.getDateList(format, startDate, endDate);
        Boolean flag = true;
        for (int i = 0; i < dateStringList.size(); i++) {
            resList.add(dateStringList.get(i));
            for (AlarmPersonCharts c : bTableList) {
                if (dateStringList.get(i).equals(c.getAlarmTime())) {
                    flag = false;
                    resList.addAll(c.getResList());
                    resList2.add(resList);
                }
            }
            for (AlarmPersonCharts c : bTableList) {
                if (flag) {
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList2.add(resList);
                    flag = false;
                }
            }

            resList = new ArrayList<>();
            flag = true;

        }
        return resList2;
    }

    private  List<List<Object>> getSelectAlarmForChartsByMonth(Date startDate,Date endDate,List<AlarmPersonCharts> bTableList) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        List<Object> resList = new ArrayList<>();
        List<List<Object>> resList2 = new ArrayList<>();
        List<String> dateStringList = new ArrayList<>();

        String beginDate =  DateUtil.formatDate(startDate);
        String lastDate = DateUtil.formatDate(endDate);
        dateStringList = Tools.getMonthList(beginDate, lastDate);
        Boolean flag = true;
        for (int i = 0; i < dateStringList.size(); i++) {
            resList.add(dateStringList.get(i));
            for (AlarmPersonCharts c : bTableList) {
                if (dateStringList.get(i).equals(c.getAlarmTime())) {
                    flag = false;
                    resList.addAll(c.getResList());
                    resList2.add(resList);
                }
            }
            for (AlarmPersonCharts c : bTableList) {
                if (flag) {
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList2.add(resList);
                    flag = false;
                }
            }

            resList = new ArrayList<>();
            flag = true;

        }
        return resList2;
    }


    /**
     * 列表明细
     */
    @Override
    public TableDataInfo selectAlarmPersonForTableDetail(AlarmPerson alarmPerson) {
        List<AlarmPersonTableDetailVO> alarmPersonTableDetailVOList = getAlarmPersonTableDetailVOS(alarmPerson);
        return Tools.buildTableDataInfo(alarmPerson.getPageNum(), alarmPerson.getPageSize(), alarmPersonTableDetailVOList);
    }
    @Override
    public List<AlarmPersonTableDetailVO> getAlarmPersonTableDetailVOS(AlarmPerson alarmPerson) {
        if (Objects.isNull(alarmPerson.getAlarmStartTime())){
            alarmPerson.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            alarmPerson.setAlarmStartTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmPerson.getAlarmStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(alarmPerson.getAlarmEndTime())){
            alarmPerson.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            alarmPerson.setAlarmEndTime(DateUtil.parseDateTime(DateUtil.formatDate(alarmPerson.getAlarmEndTime())+" 23:59:59"));
        }
        QueryWrapper<AlarmPerson> alarmPersonQueryWrapper=new QueryWrapper<>();
        if (StringUtils.isNotEmpty(alarmPerson.getPersonId())){
            alarmPersonQueryWrapper.lambda().eq(AlarmPerson::getPersonId, alarmPerson.getPersonId());
        }
        if (StringUtils.isNotEmpty(alarmPerson.getPersonName())){
            alarmPersonQueryWrapper.lambda().eq(AlarmPerson::getPersonName, alarmPerson.getPersonName());
        }
        if (StringUtils.isNotEmpty(alarmPerson.getAlarmTypeName())){
            alarmPersonQueryWrapper.lambda().eq(AlarmPerson::getAlarmTypeName, alarmPerson.getAlarmTypeName());
        }
        if (CollectionUtils.isNotEmpty(alarmPerson.getIds())){
            alarmPersonQueryWrapper.lambda().in(AlarmPerson::getAlarmPersonId, alarmPerson.getIds());
        }

        if (Objects.nonNull(alarmPerson.getAlarmStartTime())) {
            alarmPersonQueryWrapper.lambda().ge(AlarmPerson::getAlarmTime, alarmPerson.getAlarmStartTime());
        }
        if (Objects.nonNull(alarmPerson.getAlarmEndTime())) {
            alarmPersonQueryWrapper.lambda().le(AlarmPerson::getAlarmTime, alarmPerson.getAlarmEndTime());
        }
        alarmPersonQueryWrapper.lambda().orderByDesc(AlarmPerson::getAlarmTime);

        List<AlarmPerson> alarmPersonList = alarmPersonMapper.selectList(alarmPersonQueryWrapper);

        List<AlarmPersonTableDetailVO> alarmPersonTableDetailVOList = new ArrayList<>();
        alarmPersonList.forEach(t -> {
            AlarmPersonTableDetailVO alarmPersonTableDetailVO = new AlarmPersonTableDetailVO();
            alarmPersonTableDetailVO.setId(t.getAlarmPersonId());
            alarmPersonTableDetailVO.setPersonId(t.getPersonId());
            alarmPersonTableDetailVO.setPersonName(t.getPersonName());
            alarmPersonTableDetailVO.setPersonTypeName(t.getPersonTypeName());
            alarmPersonTableDetailVO.setDepName(t.getDepName());
            alarmPersonTableDetailVO.setAlarmTypeName(t.getAlarmTypeName());
            alarmPersonTableDetailVO.setAlarmStartTime(DateUtil.formatDateTime(t.getAlarmStartTime()));
            alarmPersonTableDetailVO.setAlarmEndTime(DateUtil.formatDateTime(t.getAlarmEndTime()));
            alarmPersonTableDetailVO.setContent(t.getContent());
            /** 保存地址 **/
            String currentAddress = "";
            if (StringUtils.isNotEmpty(t.getLng())&&StringUtils.isNotEmpty(t.getLat())) {
                currentAddress = locationUtil.getAddress(t.getLng(), t.getLat());
            }
            if (StringUtils.isNotEmpty(currentAddress)) {
                alarmPersonTableDetailVO.setAddress(currentAddress);
            } else {
                alarmPersonTableDetailVO.setAddress("");
            }
            alarmPersonTableDetailVOList.add(alarmPersonTableDetailVO);
        });
        return alarmPersonTableDetailVOList;
    }
}
